﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Data.Sql;
using Djs.Neuronic.Brain;
using Djs.Neuronic.Core;

namespace Djs.Neuronic.Brain
{
    public partial class SettingCls : CommonCls
    {
        #region Konstrukce
        protected override void Init()
        {
            this.CfgFile = System.IO.Path.Combine(this.Creator.AppPath, this.Creator.AppName) + ".config.xml";
        }
        internal override void Prepare()
        {
            this.CfgLoad();
        }
        private string CfgFile;
        #endregion
        #region Konfigurace
        public void CfgLoad()
        {
            this.CfgClear();
            if (System.IO.File.Exists(this.CfgFile))
            {
                XDocument xDoc = XDocument.Load(this.CfgFile);
                XElement xRoot = xDoc.Root;

                XElement xDbs = xRoot.Element("dbs");
                string conection = xDbs.GetAttributeString("Conection");
                bool isCrypt = xDbs.GetAttributeBoolean("IsCrypt");
                if (isCrypt)
                    this._ConnectionString = (string)Convertor.StringToPassword(conection);
                else
                    this._ConnectionString = conection;

            }
            this.CheckConnectString();
            this.Database.ConnectString = this.ConnectionString;
        }
        public void CfgSave()
        {
            XDocument xDoc = new XDocument(new XElement("config"));

            XElement xDbs = new XElement("dbs");
            xDbs.AddAttribute("Conection", Convertor.PasswordToString(this._ConnectionString));
            xDbs.AddAttribute("IsCrypt", true);
            xDoc.Root.Add(xDbs);

            xDoc.Save(this.CfgFile, true);
        }
        public void CfgClear()
        {
            this._ConnectionString = null;
        }
        /// <summary>
        /// Metoda ověří správnost ConnectionStringu (prostřednictvím objektu Database), případně zajistí dialogové okno s určením připojení k databázi
        /// </summary>
        private void CheckConnectString()
        {
            string newConnectString = this.Database.CheckConnectString(this._ConnectionString, true);
            if (newConnectString != null)
                this.ConnectionString = newConnectString;               // set {} vyvolá CfgSave.
        }
        #endregion
        #region Property
        public string ConnectionString { get { return _ConnectionString; } set { _ConnectionString = value; this.CfgSave(); } }
        private string _ConnectionString;
        #endregion
    }
}
